package com.zjl.Kafka.第04章_分布式扩展;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.kafka.support.SendResult;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class S_kafkaController {
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @ResponseBody
    @PostMapping("/kafka/add")
    public String add(@RequestBody Map<String ,Object> body) throws ExecutionException, InterruptedException {
        CompletableFuture<SendResult<String, String>> kafkaBoot = kafkaTemplate.send("kafkaBoot", body.toString());

        return kafkaBoot.get().toString();
    }

    //                 监听的主题
    @KafkaListener(topics = {"kafkaBoot"},groupId = "kafkaGroup")
    public void topic_test(List<String> messages, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic){
        for (String message:messages){
            System.out.print("\u001B[35m");
            System.out.print("kafkaGroup 消费了 主题为" + topic + "的数据：" + message);
            System.out.println("\u001B[0m");
        }
    }
}
